package com.shungen.apicloud.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shungen.apicloud.annotation.AuthCheck;
import com.shungen.apicloud.common.BaseResponse;
import com.shungen.apicloud.common.DeleteRequest;
import com.shungen.apicloud.common.ErrorCode;
import com.shungen.apicloud.common.ResultUtils;
import com.shungen.apicloud.constant.UserConstant;
import com.shungen.apicloud.exception.BusinessException;
import com.shungen.apicloud.exception.ThrowUtils;
import com.shungen.apicloud.model.dto.interfaceinfo.InterfaceInfoAddRequest;
import com.shungen.apicloud.model.dto.interfaceinfo.InterfaceInfoQueryRequest;
import com.shungen.apicloud.model.dto.interfaceinfo.InterfaceInfoUpdateRequest;
import com.shungen.apicloud.model.entity.InterfaceInfo;
import com.shungen.apicloud.model.entity.InterfaceLabel;
import com.shungen.apicloud.model.entity.InterfaceLabelRelationship;
import com.shungen.apicloud.model.entity.InterfaceParamText;
import com.shungen.apicloud.model.vo.InterfaceInfoVO;
import com.shungen.apicloud.service.*;
import com.shungen.apicloud.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author shungen
 * @date 2024年07月23日 9:40
 */
@RestController
@RequestMapping("/interfaceInfo")
@Slf4j
public class InterfaceInfoController {

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Resource
    private InterfaceLabelService interfaceLabelService;

    @Resource
    private InterfaceLabelRelationshipService interfaceLabelRelationshipService;

    @Resource
    private UserService userService;




    // region 增删改查

    /**
     * 管理员新增接口信息，这里需要传入其应该携带的标签
     * @param interfaceInfoAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public BaseResponse<Long> addInterfaceInfo(@RequestBody InterfaceInfoAddRequest interfaceInfoAddRequest, HttpServletRequest request) {
        //1.校验参数
        if (interfaceInfoAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //2.取数据
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoAddRequest,interfaceInfo);
        interfaceInfoService.validInterfaceInfo(interfaceInfo,true);

        //处理参数说明
        InterfaceParamText paramText = new InterfaceParamText();
        paramText.setParamText(interfaceInfoAddRequest.getParamText());
        boolean saveParamTextRes = interfaceParamTextService.save(paramText);
        ThrowUtils.throwIf(!saveParamTextRes,ErrorCode.OPERATION_ERROR,"保存参数文档失败");
        interfaceInfo.setParamTextId(paramText.getId());


        //3.先新增接口
        //执行插入
        String token = request.getHeader("token");
        Long userId = Long.valueOf(JWTUtil.getClaimFromToken(token, "id"));
        interfaceInfo.setUserId(userId);
        boolean result = interfaceInfoService.save(interfaceInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        Long newInterfaceInfoId = interfaceInfo.getId();//获取新增接口信息的接口id


        //处理标签信息
        List<Long> interfaceLabelIdList = interfaceInfoAddRequest.getInterfaceLabelIdList();
        if(!(interfaceLabelIdList == null || interfaceLabelIdList.size() == 0)){
            //添加标签数据
            List<InterfaceLabelRelationship> interfaceLabelRelationshipList = new ArrayList<>(interfaceLabelIdList.size());
            InterfaceLabelRelationship relationship = null;
            for(int i = 0;i < interfaceLabelIdList.size();i++){
                relationship = new InterfaceLabelRelationship();
                relationship.setInterfaceId(newInterfaceInfoId);
                relationship.setLabelId(interfaceLabelIdList.get(i));
                interfaceLabelRelationshipList.add(relationship);
            }
            // 打印要保存的关系数据
//            System.out.println("开始打印");
//            for (InterfaceLabelRelationship r : interfaceLabelRelationshipList) {
//                System.out.println("Saving relationship: " + r);
//            }
//            System.out.println("结束打印");

            boolean resultLabel = interfaceLabelRelationshipService.saveBatch(interfaceLabelRelationshipList);
//            System.err.println(resultLabel + " ============ resultLabel");
            ThrowUtils.throwIf(!resultLabel,ErrorCode.OPERATION_ERROR,"为接口添加标签失败");
        }




        return ResultUtils.success(newInterfaceInfoId);

    }

    /**
     * 删除接口信息(仅个人或者管理员)
     *
     * 要点:
     *  检查参数->检查是否登录->检查操作对象是否存在->检查用户权限->执行删除-->返回结果(数据为boolean类型)
     *  删除所依赖的接口标签联系 ->删除接口信息
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public BaseResponse<Boolean> deleteInterfaceInfo(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 1.判断接口是否存在
        Long id = deleteRequest.getId();
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        ThrowUtils.throwIf(interfaceInfo == null,ErrorCode.NOT_FOUND_ERROR);

        //2.删除标签联系
        List<Long> relationShipIdByInterfaceIdList = interfaceLabelRelationshipService.getRelationShipIdByInterfaceId(id);
        if(!(relationShipIdByInterfaceIdList == null || relationShipIdByInterfaceIdList.size() == 0)){
            //删除标签
            boolean resultRemoveLabel = interfaceLabelRelationshipService.removeBatchByIds(relationShipIdByInterfaceIdList);
            ThrowUtils.throwIf(!resultRemoveLabel,ErrorCode.OPERATION_ERROR,"删除接口对应标签信息失败");
        }
        boolean result = interfaceInfoService.removeById(id);
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR,"删除接口信息失败");
        return ResultUtils.success(true);
    }

    /**
     *
     * 更新接口信息(仅管理员)，不更新标签信息
     * @param interfaceInfoUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateInterfaceInfo(@RequestBody InterfaceInfoUpdateRequest interfaceInfoUpdateRequest) {
        if (interfaceInfoUpdateRequest == null || interfaceInfoUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //创建更新接口信息参数对象
        InterfaceInfo interfaceInfo = new InterfaceInfo();
        BeanUtils.copyProperties(interfaceInfoUpdateRequest,interfaceInfo);
        InterfaceInfo oldInterfaceInfo = interfaceInfoService.getById(interfaceInfo.getId());
        ThrowUtils.throwIf(oldInterfaceInfo == null,ErrorCode.NOT_FOUND_ERROR,"目标接口信息不存在");

        //执行更新接口信息
        boolean result = interfaceInfoService.updateById(interfaceInfo);
        return ResultUtils.success(result);
    }

    /**
     * 根据接口id查询接口信息【允许未登录】设定为在线调用的时候进行要求登录
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<InterfaceInfoVO> getInterfaceInfoById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求参数错误");
        }
        //先去执行查询
        System.err.println("根据id查询接口信息收到的id = " + id);
        InterfaceInfo interfaceInfo = interfaceInfoService.getById(id);
        ThrowUtils.throwIf(interfaceInfo == null,ErrorCode.NOT_FOUND_ERROR,"查询目标接口信息不存在");

        InterfaceInfoVO interfaceInfoVO = new InterfaceInfoVO();
        //查询绑定的标签信息
        List<Long> interfaceLabelIdList = interfaceLabelRelationshipService.getInterfaceLabelIdByInterfaceId(interfaceInfo.getId());
        if(interfaceLabelIdList.size() != 0){
            //执行查询
            List<InterfaceLabel> interfaceLabelList = interfaceLabelService.getByIdList(interfaceLabelIdList);
            List<String> collect = interfaceLabelList.stream().map(InterfaceLabel::getLabelName).collect(Collectors.toList());
            interfaceInfoVO.setInterfaceLabelList(collect);
        }
        BeanUtils.copyProperties(interfaceInfo,interfaceInfoVO);
        return ResultUtils.success(interfaceInfoVO);
    }

    @PostMapping("/list/page")
    public BaseResponse<Page<InterfaceInfoVO>> getInterfaceVOListWithPage(@RequestBody InterfaceInfoQueryRequest interfaceInfoQueryRequest){
        //1.检查参数
        ThrowUtils.throwIf(interfaceInfoQueryRequest == null,ErrorCode.PARAMS_ERROR,"请求参数错误");
        if(interfaceInfoQueryRequest.getPageSize() <= 0){
            interfaceInfoQueryRequest.setPageSize(10);
        }
        if(interfaceInfoQueryRequest.getCurrent() <= 0){
            interfaceInfoQueryRequest.setCurrent(1);
        }
        InterfaceInfoVO interfaceInfoVO = new InterfaceInfoVO();
        BeanUtils.copyProperties(interfaceInfoQueryRequest,interfaceInfoVO);
        //2.查询接口分页数据
        Page<InterfaceInfo> interfaceInfoPage = interfaceInfoService.selectPage(interfaceInfoQueryRequest, interfaceInfoQueryRequest.getPageSize(), interfaceInfoQueryRequest.getCurrent());
        //
        List<InterfaceInfo> interfaceInfoList = interfaceInfoPage.getRecords();
        System.err.println("查询到的接口信息列表为:" + interfaceInfoList);
        List<InterfaceInfoVO> newRecord = interfaceInfoList.stream().map(interfaceInfo -> {
            InterfaceInfoVO interfaceInfoVOInner = new InterfaceInfoVO();
            BeanUtils.copyProperties(interfaceInfo, interfaceInfoVOInner);
            //去查询对应的标签信息
            List<Long> interfaceLabelIds = interfaceLabelRelationshipService.getInterfaceLabelIdByInterfaceId(interfaceInfoVOInner.getId());
            System.out.println("查询到的接口标签id列表:" + interfaceLabelIds);
            if(interfaceLabelIds == null || interfaceLabelIds.size() == 0){
                //没有标签信息
            }else{
                List<InterfaceLabel> interfaceLabelList = interfaceLabelService.getByIdList(interfaceLabelIds);
                List<String> collect = interfaceLabelList.stream().map(InterfaceLabel::getLabelName).collect(Collectors.toList());
                interfaceInfoVOInner.setInterfaceLabelList(collect);
            }
            return interfaceInfoVOInner;
        }).collect(Collectors.toList());
        Page<InterfaceInfoVO> result = new Page<>(interfaceInfoQueryRequest.getPageSize(),interfaceInfoQueryRequest.getCurrent());
        BeanUtils.copyProperties(interfaceInfoPage,result);
        result.setRecords(newRecord);
        return ResultUtils.success(result);
    }
    // endregion


    @Resource
    private InterfaceParamTextService interfaceParamTextService;
    @GetMapping("/paramText")
    public BaseResponse<String> getInterfaceParamDescription(@RequestParam("paramTextId")Long paramTextId){
        //直接根据id查询数据
        InterfaceParamText paramText = interfaceParamTextService.getById(paramTextId);
        ThrowUtils.throwIf(paramText == null,ErrorCode.PARAMS_ERROR,"参数文档不存在");
        return ResultUtils.success(paramText.getParamText());
    }

}
